<html>
  <head>
    <meta charset="utf-8">
    <title>Mongoose ODM</title>
    <style>
      body {
        background: url('/docs/2.7.x/images/bg.png');
        padding: 0 30px 30px;
        margin-top: 0;
      }

      #wrap {
        background: url('/docs/2.7.x/images/pattern.png') no-repeat -134px -211px;
        min-height: 600px;
        padding-top: 30px;
      }

      #page {
        width: 650px;
        margin: auto;
        position: relative;
      }

      #footer {
        font: 13px Helvetica;
        padding-top: 15px;
        border-top: 1px solid #000;
        color: #666;
        margin-top: 25px;
      }

      #footer > div {
        padding-top: 8px;
        float: right;
        text-align: right;
        padding-bottom: 20px;
      }

      #content {
        color: #111;
        font: 15px Courier;
      }

      #content h1, #content h2, #content h3 {
        text-shadow: 0 1px 0 #fff;
      }

      #announce {
        background: #2A758A;
        border: 10px solid black;
        border-radius: 7px;
        padding: 30px;
        font-size: 125%;
        color: white;
        text-shadow: none;
        font-family: Arial;
      }

      #announce a {
        color: orange;
        text-shadow: none;
      }

      pre {
        background: rgba(255,255,255,.8);
        border: 1px solid #c6c6c6;
        padding: 10px;
        border-radius: 3px;
        box-shadow: 1px 3px 6px #ddd;
      }

      code {
        background: rgba(255,255,255,.8);
        border: 1px solid #c6c6c6;
        color: #333;
        border-radius: 3px
      }

      pre code {
        border: 0 none;
      }

      form {
        font: bold 12px Helvetica;
        text-shadow: 0 1px 0 #fff;
        float: left;
        padding-bottom: 25px;
      }

      form img {
        margin-right: 5px
      }

      #google-members-count {
        vertical-align: top;
        line-height: 32px;
      }

      h1 a {
        background: url('/docs/2.7.x/images/logo.png');
        width: 404px;
        height: 47px;
        margin-bottom: 40px;
        text-indent: -500em;
        display: block;
      }

      a {
        color: #2a758a;
        text-shadow: 0 1px 0 #fff;
        text-decoration: none;
      }

      a:hover {
        opacity: 0.8;
      }

      #menu {
        position: fixed;
        top: 0;
        left: 0;
        height: 100%;
        background-color: rgba(0,0,0,0.3);
        font: bold 15px Helvetica;
        border-right: 1px solid rgba(0,0,0,0.2);
      }

      #menu ul {
        margin: 0;
        padding: 50px 0;
      }

      #menu ul li {
        list-style-type: none;
        padding-left: 15px;
        padding-right: 20px;
      }

      #menu ul li a {
        color: #fff;
        text-shadow: none;
      }
      #menu ul li a:hover {
        text-decoration: underline;
      }
      #wild { margin-top: 10px; }
    </style>

    <script>
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-1122274-9']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
      
      function getMembers(data){
        if (!(data && data.query && data.query.results && data.query.results.p)) return;
        var members = document.createElement('span');
        members.id = 'google-members-count';
        members.innerHTML = '('+ data.query.results.p +' members)';
        document.getElementsByTagName('FORM')[0].insertBefore(members, document.getElementById('google-subscribe-input'));
      };

      window.onload = function(){
        // lame jsonp
        var script = document.createElement('script');
        script.src = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fgroups.google.com%2Fgroup%2Fmongoose-orm%2Fabout%22%20and%20xpath%3D'%2F%2Fdiv%5B%40class%3D%5C'maincontbox%5C'%5D%2Ftable%2Ftr%5B1%5D%2Ftd%2Fp%5B1%5D'%0A&format=json&callback=getMembers";
        document.head.appendChild(script);
      };
    </script>
  </head>
  <body>
    <a href="http://github.com/learnboost/mongoose"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
    <div id="wrap">
      <div id="page">
        <div id="menu">
          <ul>
            <li><a href="../index.html">Home</a></li>
            <li><a href="model-definition.html">Models/Schemas</a></li>
            <li><a href="schematypes.html">Schema Types</a></li>
            <li><a href="schema-options.html">Schema Options</a></li>
            <li><a href="middleware.html">Middleware</a></li>
            <li><a href="finding-documents.html">Finding Docs</a></li>
            <li><a href="updating-documents.html">Updating Docs</a></li>
            <li><a href="query.html">Queries</a></li>
            <li><a href="querystream.html">Query Streams</a></li>
            <li><a href="methods-statics.html">Methods &amp; Statics</a>
            <li><a href="defaults.html">Defaults</a></li>
            <li><a href="indexes.html">Indexes</a></li>
            <li><a href="validation.html">Validation</a></li>
            <li><a href="virtuals.html">Virtuals</a></li>
            <li><a href="getters-setters.html">Getters / Setters</a></li>
            <li><a href="embedded-documents.html">Embedded Docs</a></li>
            <li><a href="populate.html">Populate (DBRef-like)</a></li>
            <li><a href="plugins.html">Plugins</a></li>
            <li><a href="errors.html">Errors</a></li>
            <li><a href="migration-1x-2x.html">v1x - v2x Migration</a></li>
            <li><a href="api.html">API</a></li>
          </ul>
        </div>

        <h1><a href="../index.html">Mongoose</a></h1>

        <div id="content">
          <!-- ANNOUNCE -->
          <h1>QueryStreams</h1>

<p><em>New in 2.4.0</em></p>

<p>A QueryStream provides a ReadStream interface for <a href="query.html">Queries</a>. The Stream interface allows us to simply "plug-in" to other Node streams such as http responses and write streams so everything "just works" out of the box.</p>

<pre><code>Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream);
</code></pre>

<p>This api provides a more natural node-like api than than what is presently available with the <a href="query.html">Query#each</a> method.</p>

<pre><code>var stream = Model.find().stream();

stream.on('data', function (doc) {
  if (somethingHappened) {
    this.pause()

    var self = this
    return bakeSomePizza(function () {
      self.resume()
    })
  }

  res.write(doc)
})

stream.on('error', function (err) {
  // handle err
})

stream.on('close', function () {
  // all done
})
</code></pre>

<p>QueryStreams can be <code>pause</code>d and <code>resume</code>d like you’d expect which allows us to stop streaming while waiting for other processes to complete for example.</p>

<p>QueryStreams also manage the underlying Cursors better than what we had in <code>Query#each</code> such that after the QueryStream has completed, whether due to an error, reaching the end of the cursor, or being manually destroyed, the internal Cursor is properly cleaned up.</p>

<h1>Events</h1>

<h2>data</h2>

<p>The <code>data</code> event emits a Mongoose Document as its only argument.</p>

<pre><code>stream.on('data', function (doc) { });
</code></pre>

<h2>error</h2>

<p>Emitted if an error occurs while streaming documents. This event will fire <em>before</em> the <code>close</code> event.</p>

<h2>close</h2>

<p>Emitted when the stream reaches the end of the cursor, or an error occurs, or the stream is manually <code>destroy</code>ed. After this event, no more events will be emitted.</p>

<h1>Properties</h1>

<h2>QueryStream.readable</h2>

<p>Boolean, tells us if the stream is readable or not. <code>true</code> by default, <code>false</code> after calling <code>destroy</code> or an error occurs or the stream is closed.</p>

<pre><code>var stream = Model.find().stream();
stream.readable // true
</code></pre>

<h2>QueryStream.paused</h2>

<p>Boolean, tells us if the stream is currently paused.</p>

<pre><code>var stream = Model.find().stream()
stream.paused // false
stream.pause()
stream.paused // true
</code></pre>

<h1>Methods</h1>

<h2>QueryStream#pause</h2>

<p>Pauses the stream. <code>data</code> events will stop until <code>resume()</code> is<br />called.</p>

<pre><code>stream.pause();
</code></pre>

<h2>QuerySteam#resume</h2>

<p>Resumes the QueryStream.</p>

<pre><code>stream.resume()
</code></pre>

<h2>QueryStream#destroy</h2>

<p>Destroys the stream. No more events will be emitted after<br />calling this method.</p>

<pre><code>stream.destroy([err])
</code></pre>

<p>If the optional <code>err</code> argument is passed, an <code>error</code> event will be emitted with the <code>err</code> before <code>close</code> is emitted.</p>

<h2>QueryStream#pipe</h2>

<p><code>pipe</code>s the QueryStream into another WritableStream. This method is inherited from <a href="http://nodejs.org/docs/latest/api/streams.html#stream.pipe">Stream</a>.</p>

<pre><code>Model.find().stream().pipe(writeStream [, options]);
</code></pre>

<p>This could be particularily useful if you are, for example, setting up an API for a service and want to stream out the docs based on some criteria. We could first pipe the QueryStream into a sort of filter that formats the stream as an array before passing on the document to an http response.</p>

<pre><code>var format = new ArrayFormatter;
Events.find().stream().pipe(format).pipe(res);
</code></pre>

<p>As long as <code>ArrayFormat</code> implements the WriteStream API we can stream large formatted result sets out to the client. See this <a href="https://gist.github.com/1403797">gist</a> for a hacked example.</p>
        </div>

        <div id="footer">

          <form action="http://groups.google.com/group/mongoose-orm/boxsubscribe">
           <a href="http://groups.google.com/group/mongoose-orm" id="google-subscribe-link"><img src="/docs/2.7.x/images/groups.png" border="0"></a>
           <span id="google-members-count">&nbsp;</span>
           <div id="google-subscribe-input">
             Email: <input type="text" name="email" id="google-subscribe-email">
             <input type="submit" name="go" value="Subscribe">
           </div>
          </form>

          <div>
            Mongoose by <a href="http://github.com/learnboost">LearnBoost Labs</a>.<br>
            Released under the MIT license.<br>
            Copyright <a href="http://learnboost.com">LearnBoost 2011</a>.
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
